package com.runen.wnhz.runen.ui.activity.main;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.bean.HotHistorySearchBean;
import com.runen.wnhz.runen.common.utils.ACacheUtlis;
import com.runen.wnhz.runen.common.utils.NetUtils;
import com.runen.wnhz.runen.common.utils.OkHttpUtils;
import com.runen.wnhz.runen.common.utils.StatusBarCompatUtils;
import com.runen.wnhz.runen.common.utils.ToastUtil;
import com.runen.wnhz.runen.di.component.ApplicationComponent;
import com.runen.wnhz.runen.ui.activity.BaseActivity;
import com.runen.wnhz.runen.ui.activity.BasicActivity;
import com.runen.wnhz.runen.ui.adapter.puadapter.HotSearchAdapter;
import com.runen.wnhz.runen.ui.adapter.puadapter.UserSearchHisAdapter;
import com.runen.wnhz.runen.widget.TitleBuilder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2018/6/1 0001.
 */

public class SearchActivity extends BasicActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.list_hotSearch)
    ListView listHotSearch;
    @BindView(R.id.image_delHistorySearch)
    ImageView imageDelHistorySearch;
    @BindView(R.id.list_historySearch)
    ListView listHistorySearch;
    @BindView(R.id.edit_search)
    EditText editSearch;
    private List<String> searchHot;
    private List<HotHistorySearchBean.DataBean.MySearchBean> mySearch;
    private UserSearchHisAdapter adapter;

    @OnClick({R.id.iv_back, R.id.image_delHistorySearch})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.image_delHistorySearch:
                if(adapter != null){
                    mySearch.clear();
                    adapter.notifyDataSetChanged();
                }
                break;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        StatusBarCompatUtils.getInstance().TranslucentStatusBar(this, R.color.title_green);
        mySearch = new ArrayList<>();
        setListener();
        getHotAndHistorySearch();
    }

    private void startSearchResultActivity(String so){
        Intent intent = new Intent(this,SearchResultActivity.class);
        intent.putExtra("so",so);
        intent.putExtra("type","1");
        startActivity(intent);
    }

    private void setListener() {
        listHotSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                String so = searchHot.get(position);
                startSearchResultActivity(so);
            }
        });
        listHistorySearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                HotHistorySearchBean.DataBean.MySearchBean mySearchBean = mySearch.get(position);
                String so = mySearchBean.getContent();
                startSearchResultActivity(so);
            }
        });
        editSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && keyEvent.getAction() == KeyEvent.ACTION_DOWN){
                    /*隐藏软键盘*/
                    InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (inputMethodManager.isActive()) {
                        inputMethodManager.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);//隐藏软键盘
                    }
                    if(TextUtils.isEmpty(editSearch.getEditableText().toString())){
                        ToastUtil.showToast("请输入您要搜索的内容");
                    }else {
                        Intent searchIntent = new Intent(SearchActivity.this, SearchResultActivity.class);
                        String keyWord = editSearch.getEditableText().toString().trim();//将用户输入文字的前后空格去掉
                        searchIntent.putExtra("so", keyWord);
                        searchIntent.putExtra("type","1");
                        startActivity(searchIntent);
                    }
                    return true;
                }
                return false;
            }
        });
    }

    private void getHotAndHistorySearch() {

        if(null != ACacheUtlis.getInstance().getReqeustUser(this) && ACacheUtlis.getInstance().getReqeustUser(this).getToken() != null) {
            showProgressDialog();
            FormBody formBody = new FormBody.Builder().add("token", ACacheUtlis.getInstance().getReqeustUser(this).getToken()).build();
            System.out.println("token == " + ACacheUtlis.getInstance().getReqeustUser(this).getToken());
            //构建一个网络请求，从指定网址上面请求数据
            Request.Builder requestBuilder = new Request.Builder().url(NetUtils.GET_HOT_AND_HISTORY_URL).post(formBody);
            //创建Call对象
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(requestBuilder.build());
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("数据请求失败");
                        }
                    });
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                handleData(response);
                            } catch (IOException e) {
                                ToastUtil.showToast("数据请求出现异常");
                                e.printStackTrace();
                            }
                        }
                    });
                }
            });
        }

    }

    private void handleData(Response response) throws IOException {
        if (response.isSuccessful()) {//数据请求成功
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String json = responseBody.string();
                System.out.println("[[[[[[[[[[ == " + json);
                HotHistorySearchBean hotHistorySearchBean = new Gson().fromJson(json, HotHistorySearchBean.class);
                dismissDialog();
                if (hotHistorySearchBean != null) {
                    if ("0".equals(hotHistorySearchBean.getRe())) {
                        ToastUtil.showToast(hotHistorySearchBean.getInfo());
                    } else if ("1".equals(hotHistorySearchBean.getRe())) {
                        searchHot = hotHistorySearchBean.getData().getSearch_hot();
                        listHotSearch.setAdapter(new HotSearchAdapter(searchHot, SearchActivity.this));
                        mySearch.addAll(hotHistorySearchBean.getData().getMy_search());
                        adapter = new UserSearchHisAdapter(mySearch, SearchActivity.this);
                        listHistorySearch.setAdapter(adapter);
                    }
                }
            }
        }
    }

}
